package com.example.myapplication.LoginRegister;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.Tool.NetworkErrorTool;
import com.example.myapplication.R;
import com.example.myapplication.http.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {

    private final Gson gson = new Gson();
    private EditText username,identity,userpwd,userpwd2;
    String identityID;
    private EditText pwd;
    private Button submit;
    private TextView tvreg;
    private int code;// 响应码
    private String msg;// 提示信息
    private Boolean bPwdSwitch = false;
//    Mysql mysql;
//    private SQLiteDatabase db;
//    private SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        username = findViewById(R.id.et_account);
        identity = findViewById(R.id.et_identity);
        userpwd = findViewById(R.id.et_pwd);
        userpwd2 = findViewById(R.id.et_pwd_confirm);
        submit = findViewById(R.id.bt_register);
        tvreg = findViewById(R.id.tv_login);
        final ImageView ivPwdSwitch = findViewById(R.id.iv_pwd_switch);
        final ImageView ivPwdSwitch2 = findViewById(R.id.iv_pwd_switch_confirm);

//        mysql = new Mysql(this,"Userinfo",null,1);
//        db = mysql.getReadableDatabase();
//        sp = this.getSharedPreferences("useinfo",this.MODE_PRIVATE);


//        submit.setOnClickListener(new View.OnClickListener() {
//            boolean flag =true;
//            @Override
//            public void onClick(View view) {
//                String name = username.getText().toString();
//                String pwd1 = userpwd.getText().toString();
//                String pwd2 = userpwd2.getText().toString();
//                if(name.equals("")||pwd1.equals("")||pwd2.equals("")){
//                    Toast.makeText(RegisterActivity.this, "用户名或密码不能为空!！", Toast.LENGTH_LONG).show();
//                }
//                else {
//                    Cursor cursor = db.query("logins",new String[]{"usname"},null,null,null,null,null);
//
//                    while(cursor.moveToNext()){
//                        if(cursor.getString(0).equals(name)){
//                            flag = false;
//                            break;
//                        }
//                    }
//                    if(flag==true){
//                        if (pwd1.equals(pwd2)){
//                            ContentValues contentValues =new ContentValues();
//                            contentValues.put("usname",name);
//                            contentValues.put("uspwd",pwd1);
//                            db.insert("logins",null,contentValues);
//                            SharedPreferences.Editor editor = sp.edit();
//                            editor.putString("usname",name);
//                            editor.putString("uspwd",pwd1);
//                            editor.commit();
//                            Intent intent = new Intent();
//                            intent.setClass(RegisterActivity.this,LoginActivity.class);
//                            startActivity(intent);
//                            Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_LONG).show();
//
//                        }
//                        else{
//                            Toast.makeText(RegisterActivity.this, "密码不一致！", Toast.LENGTH_LONG).show();
//
//                        }
//                    }
//                    else {
//                        Toast.makeText(RegisterActivity.this, "用户已存在！", Toast.LENGTH_LONG).show();
//                    }
//
//                }
//            }
//        });

        //密码可视性切换
        ivPwdSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwd = userpwd;
                userPwd(ivPwdSwitch,pwd);
            }
        });
        ivPwdSwitch2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwd = userpwd2;
                userPwd(ivPwdSwitch2,pwd);
            }
        });

        //转注册界面事件
        tvreg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(RegisterActivity.this,"返回到登录界面",Toast.LENGTH_SHORT).show();
                finish();//销毁当前活动
            }
        });


        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //身份转换
                if(identity.getText().toString().equals("老师")) {
                    identityID = "1";
                } else if(identity.getText().toString().equals("学生")) {
                    identityID = "0";
                } else{
                    identityID = "3";
                }

                //身份判断
                if(identityID.equals("1")||identityID.equals("0")) {
                    //post请求
                    if(userpwd.getText().toString().equals(userpwd2.getText().toString())){
                        //注册请求
                        post();
                    } else {
                        Toast.makeText(RegisterActivity.this, "密码不统一", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Log.d("chenpengyu1111111111", identityID);
                    Toast.makeText(RegisterActivity.this, "身份认证错误，不存在该身份", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    private void post(){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/sign/user/register";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            // 请求体
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("password", userpwd.getText().toString());
            bodyMap.put("roleId", identityID);
            bodyMap.put("userName", username.getText().toString());

            // 将Map转换为字符串类型加入请求体中
            String body = gson.toJson(bodyMap);

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            Log.d("chenpengyu1111111111", String.valueOf(request));
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }
    /*** 回调*/
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            NetworkErrorTool networkErrorTool = new NetworkErrorTool(RegisterActivity.this);
            // 请求失败处理
            e.printStackTrace();
            networkErrorTool.showTimeoutDialog(); // 显示超时提示对话框
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("chenpengyu1111111111", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("chenpengyu1111111111", dataResponseBody.toString());

            // 获取响应的数据
            code = dataResponseBody.getCode();
            msg = dataResponseBody.getMsg();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    handleResponse(); // 处理响应结果
                }
            });
        }
    };
    //注册
    private void handleResponse() {
        if(code == 500){
            Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_LONG).show();
        } else if (code == 200) {
            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_LONG).show();
            Intent intent = new Intent();
            intent.setClass(RegisterActivity.this,LoginActivity.class);
            startActivity(intent);
        } else {
            Toast.makeText(RegisterActivity.this, "违规操作", Toast.LENGTH_LONG).show();
        }
    }
    private void userPwd(ImageView ivPwdSwitch , EditText pwd) {
        bPwdSwitch = !bPwdSwitch;
        if (bPwdSwitch) {
            ivPwdSwitch.setImageResource(
                    R.drawable.baseline_visibility_24);
            pwd.setInputType(
                    InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            ivPwdSwitch.setImageResource(
                    R.drawable.baseline_visibility_off_24);
            pwd.setInputType(
                    InputType.TYPE_TEXT_VARIATION_PASSWORD |
                            InputType.TYPE_CLASS_TEXT);
            userpwd.setTypeface(Typeface.DEFAULT);
        }
    }




}